package com.hengxinguotong.zhihuichengjian.ui.environment.data;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.EnvironmentStatistics;
import com.hengxinguotong.zhihuichengjian.bean.EnvironmentStatisticsRes;
import com.hengxinguotong.zhihuichengjian.customtimepicker.DatePickerActivity;
import com.hengxinguotong.zhihuichengjian.customtimepicker.bean.DayTimeEntity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.IMarket;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link EnvironmentDataStatisticsFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 * 统计分析
 */
public class EnvironmentDataStatisticsFragment extends BaseFragment{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM = "equipmentId";

    @BindView(R.id.search_date_tv)
    HXTextView searchDateTv;
    @BindView(R.id.pm10_trend_chart)
    LineChart pm10TrendChart;
    @BindView(R.id.pm25_trend_chart)
    LineChart pm25TrendChart;
    @BindView(R.id.noise_chart)
    LineChart noiseChart;
    @BindView(R.id.temperature_chart)
    LineChart temperatureChart;
    @BindView(R.id.humidity_chart)
    LineChart humidityChart;
    @BindView(R.id.wind_speed_chart)
    LineChart windSpeedChart;

    // TODO: Rename and change types of parameters
    private String equipmentId;//设备id
    private String time;//时间 格式：2019-02-23
//    private int type;//1 PM10，2 PM2.5，3 噪音，4 温度， 5 湿度， 6 风速
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    EnvironmentStatistics pm10Statistics = (EnvironmentStatistics) msg.obj;
                    if(pm10Statistics.getxData() == null || pm10Statistics.getxData().size() <= 0 ||
                            pm10Statistics.getyData() == null || pm10Statistics.getyData().size() <= 0){
                        showNoDataText(pm10TrendChart);
                    }else {
                        showLineChart(pm10TrendChart, pm10Statistics.getxData(), pm10Statistics.getyData(), "PM10", getmColor(R.color.main_color),
                                1, pm10Statistics.getWarningValue(), pm10Statistics.getAlarmValue());
                    }
                    break;
                case 2:
                    EnvironmentStatistics pm25Statistics = (EnvironmentStatistics) msg.obj;
                    if(pm25Statistics.getxData() == null || pm25Statistics.getxData().size() <= 0 ||
                            pm25Statistics.getyData() == null || pm25Statistics.getyData().size() <= 0){
                        showNoDataText(pm25TrendChart);
                    }else {
                        showLineChart(pm25TrendChart, pm25Statistics.getxData(), pm25Statistics.getyData(), "PM2.5", getmColor(R.color.main_color),
                                2, pm25Statistics.getWarningValue(), pm25Statistics.getAlarmValue());
                    }
                    break;
                case 3:
                    EnvironmentStatistics noiseStatistics = (EnvironmentStatistics) msg.obj;
                    if(noiseStatistics.getxData() == null || noiseStatistics.getxData().size() <= 0 ||
                            noiseStatistics.getyData() == null || noiseStatistics.getyData().size() <= 0){
                        showNoDataText(noiseChart);
                    }else {
                        showLineChart(noiseChart, noiseStatistics.getxData(), noiseStatistics.getyData(), "噪音", getmColor(R.color.main_color),
                                3, noiseStatistics.getWarningValue(), noiseStatistics.getAlarmValue());
                    }
                    break;
                case 4:
                    EnvironmentStatistics temperatureStatistics = (EnvironmentStatistics) msg.obj;
                    if(temperatureStatistics.getxData() == null || temperatureStatistics.getxData().size() <= 0 ||
                            temperatureStatistics.getyData() == null || temperatureStatistics.getyData().size() <= 0){
                        showNoDataText(temperatureChart);
                    }else {
                        showLineChart(temperatureChart, temperatureStatistics.getxData(), temperatureStatistics.getyData(), "温度", getmColor(R.color.main_color),
                                4, temperatureStatistics.getWarningValue(), temperatureStatistics.getAlarmValue());
                    }
                    break;
                case 5:
                    EnvironmentStatistics humidityStatistics = (EnvironmentStatistics) msg.obj;
                    if(humidityStatistics.getxData() == null || humidityStatistics.getxData().size() <= 0 ||
                            humidityStatistics.getyData() == null || humidityStatistics.getyData().size() <= 0){
                        showNoDataText(humidityChart);
                    }else {
                        showLineChart(humidityChart, humidityStatistics.getxData(), humidityStatistics.getyData(), "湿度", getmColor(R.color.main_color),
                                5, humidityStatistics.getWarningValue(), humidityStatistics.getAlarmValue());
                    }
                    break;
                case 6:
                    EnvironmentStatistics windSpeedStatistics = (EnvironmentStatistics) msg.obj;
                    if(windSpeedStatistics.getxData() == null || windSpeedStatistics.getxData().size() <= 0 ||
                            windSpeedStatistics.getyData() == null || windSpeedStatistics.getyData().size() <= 0){
                        showNoDataText(windSpeedChart);
                    }else {
                        showLineChart(windSpeedChart, windSpeedStatistics.getxData(), windSpeedStatistics.getyData(), "风速", getmColor(R.color.main_color),
                                6, windSpeedStatistics.getWarningValue(), windSpeedStatistics.getAlarmValue());
                    }
                    break;
            }
        }
    };

    /**
     * 不显示无数据的提示
     *
     * @param mChart
     */
    public static void showNoDataText(LineChart mChart) {
        mChart.clear();
        mChart.notifyDataSetChanged();
        mChart.setNoDataText("暂无数据");
//        mChart.setNoDataTextColor(Color.WHITE);
        mChart.invalidate();
    }

    public EnvironmentDataStatisticsFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param equipmentId Parameter .
     * @return A new instance of fragment EnvironmentDataStatisticsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static EnvironmentDataStatisticsFragment newInstance(String equipmentId) {
        EnvironmentDataStatisticsFragment fragment = new EnvironmentDataStatisticsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM, equipmentId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            equipmentId = getArguments().getString(ARG_PARAM);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_environment_data_statistics, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    @Override
    public void onLazyLoad() {
        initData(1);
        initData(2);
        initData(3);
        initData(4);
        initData(5);
        initData(6);
    }

    private void initView() {
        time = dateFormat(new Date());
        searchDateTv.setText(time);

        initChart(pm10TrendChart);
        initChart(pm25TrendChart);
        initChart(noiseChart);
        initChart(temperatureChart);
        initChart(humidityChart);
        initChart(windSpeedChart);
    }

    private void initData(final int type){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getChartData("搜索中…", type);
            }
        }, 500);
    }

    public void getChartData(String alert, final int type) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("equipmentId", equipmentId);//设备Id
            jsonObject.put("type", type);//1pm10，2pm2.5，3噪音，4温度，5湿度，6风速
            jsonObject.put("time", time);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/environmentAlarm/getChartData/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    EnvironmentStatisticsRes res = gson.fromJson(json, EnvironmentStatisticsRes.class);
                    if(res.getStatus() == 1){
                        Message msg = handler.obtainMessage();
                        msg.what = type;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    }else{
                        showToast(res.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    @OnClick({R.id.search_date_tv})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_date_tv:
                Intent intent = new Intent(getActivity(), DatePickerActivity.class);
                startActivityForResult(intent, 0);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(requestCode == 0 && data != null){
                DayTimeEntity selectDay = (DayTimeEntity) data.getSerializableExtra("selectDay");
                processDate(selectDay);
            }
        }
    }

    private void processDate(DayTimeEntity selectDay){
        time = dateFormat(selectDay);
        searchDateTv.setText(time);
        initData(1);
        initData(2);
        initData(3);
        initData(4);
        initData(5);
        initData(6);
    }

    private String dateFormat(DayTimeEntity dayTimeEntity){
        StringBuffer dateSb = new StringBuffer();
        dateSb.append(dayTimeEntity.getYear() + "-");
        if(dayTimeEntity.getMonth() > 9){
            dateSb.append(dayTimeEntity.getMonth() + "-");
        }else {
            dateSb.append( "0" + dayTimeEntity.getMonth() + "-");
        }
        if(dayTimeEntity.getDay() > 9){
            dateSb.append(dayTimeEntity.getDay());
        }else {
            dateSb.append( "0" + dayTimeEntity.getDay());
        }
        return dateSb.toString();
    }

    private String dateFormat(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     * 初始化图表
     */
    private void initChart(LineChart lineChart) {
        /***图表设置***/
        //修改背景色
        lineChart.setBackgroundColor(Color.WHITE);
        //是否显示边界
        lineChart.setDrawBorders(false);
        //是否展示网格线
        lineChart.setDrawGridBackground(false);
        //是否可以拖动
        lineChart.setDragEnabled(true);
        //是否可以双击缩放
        lineChart.setDoubleTapToZoomEnabled(true);
        //是否有触摸事件
        lineChart.setTouchEnabled(true);
        //设置无数据状态
//        lineChart.setNoDataText("无数据");
//        lineChart.setNoDataTextColor();
//        lineChart.setNoDataTextTypeface();

        //设置XY轴动画效果
        lineChart.animateY(2500);
        lineChart.animateX(1500);

        /***XY轴的设置***/
        XAxis xAxis = lineChart.getXAxis(); //X轴
        YAxis leftYAxis = lineChart.getAxisLeft();//左侧Y轴
        YAxis rightYaxis = lineChart.getAxisRight();//右侧Y轴
        xAxis.setTextSize(10f);
        leftYAxis.setTextSize(10f);
        rightYaxis.setTextSize(10f);
        //是否显示X Y轴自己的网格线
        xAxis.setDrawGridLines(false);
        rightYaxis.setDrawGridLines(false);
        leftYAxis.setDrawGridLines(false);
        //设置X Y轴网格线为虚线（实体线长度、间隔距离、偏移量：通常使用 0）
        leftYAxis.enableGridDashedLine(10f, 10f, 0f);
        //去掉右侧Y轴
        rightYaxis.setEnabled(false);
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        //设置X轴分割数量
        xAxis.setLabelCount(7,false);
        //将Y轴分为 5份
        leftYAxis.setLabelCount(5, false);
        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);
//        rightYaxis.setAxisMinimum(0f);
        //设置图表起点从0开始
        leftYAxis.setStartAtZero(true);

//        // 设置x轴的LimitLine，index是从0开始的
//        LimitLine xLimitLine = new LimitLine(4f,"xL 测试");
//        xLimitLine.setLineColor(Color.GREEN);
//        xLimitLine.setTextColor(Color.GREEN);
//        xAxis.addLimitLine(xLimitLine);
//
//        // 设置x轴的LimitLine
//        LimitLine yLimitLine = new LimitLine(50f,"yLimit 测试");
//        yLimitLine.setLineColor(Color.RED);
//        yLimitLine.setTextColor(Color.RED);
//        leftYAxis.addLimitLine(yLimitLine);
//        setStartAtZero(boolean enabled) : 设置为 true，则无论图表显示的是哪种类型的数据，该轴最小值总是0 。
        leftYAxis.setAxisMaximum(100f);//: 设置该轴的最大值。 如果设置了，这个值将不会是根据提供的数据计算出来的。设置最小值最大值需要搭配使用才能生效。
//        resetAxisMaxValue() : 调用此方法撤销先前设置的最大值。 通过这样做，你将再次允许轴自动计算出它的最大值。
        leftYAxis.setAxisMinimum(0f);// : 设置该轴的自定义最小值。 如果设置了，这个值将不会是根据提供的数据计算出来的。
//        resetAxisMinValue() : 调用此撤销先前设置的最小值。 通过这样做，你将再次允许轴自动计算它的最小值。设置最小值最大值需要搭配使用才能生效。

        leftYAxis.setSpaceTop(20f);//: 设置图表中的最高值的顶部间距占最高值的值的百分比（设置的百分比 = 最高柱顶部间距/最高柱的值）。默认值是10f，即10% 。
        leftYAxis.setSpaceBottom(0f);

        //设置描述信息
        Description description = new Description();
        description.setText("");
        lineChart.setDescription(description);

        /***折线图例 标签 设置***/
        Legend legend = lineChart.getLegend();//图例
        //设置显示类型，LINE CIRCLE SQUARE EMPTY 等等 多种方式，查看LegendForm 即可
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(10f);
        //显示位置 左下方
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
        //是否显示图例
        legend.setEnabled(true);

    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     *
     * @param lineDataSet 线条
     * @param color       线条颜色
     * @param mode
     */
    private void initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
        //设置曲线颜色
        lineDataSet.setColor(color);
        //设置曲线圆点颜色
        lineDataSet.setCircleColor(color);
        //设置曲线宽度
        lineDataSet.setLineWidth(1f);
        //设置曲线圆点半径
        lineDataSet.setCircleRadius(1.5f);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(true);
        //设置曲线节点值字体大小
        lineDataSet.setValueTextSize(10f);
        //设置折线图填充
        lineDataSet.setDrawFilled(false);
        lineDataSet.setFormLineWidth(1f);
        lineDataSet.setFormSize(15.f);
        if (mode == null) {
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        } else {
            lineDataSet.setMode(mode);
        }
    }

    /**
     * 展示曲线
     *
     * @param xData x轴数据集合
     * @param yData y轴数据集合
     * @param name     曲线名称
     * @param color    曲线颜色
     * @param type    表格类型
     */
    public void showLineChart(LineChart lineChart, final List<String> xData, List<Float> yData, String name, int color, final int type, float warningValue, float alarmValue) {
        YAxis leftYAxis = lineChart.getAxisLeft();
        //可以设置一条警戒线，如下：
        LimitLine warningLine = new LimitLine(warningValue);//预警线
        warningLine.setLineColor(getmColor(R.color.color_FD9D00));
        warningLine.setLineWidth(1f);
        warningLine.setTextColor(getmColor(R.color.color_FD9D00));
        warningLine.setTextSize(10f);
        leftYAxis.addLimitLine(warningLine);
        LimitLine alarmLine = new LimitLine(alarmValue);//报警线
        alarmLine.setLineColor(getmColor(R.color.color_F5573F));
        alarmLine.setLineWidth(1f);
        alarmLine.setTextColor(getmColor(R.color.color_F5573F));
        alarmLine.setTextSize(10f);
        leftYAxis.addLimitLine(alarmLine);

        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < yData.size(); i++) {
            float data = yData.get(i);
            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */
            Entry entry = new Entry(i, data);
            entries.add(entry);
            if(data > 0){
                leftYAxis.resetAxisMaximum();//调用此方法撤销先前设置的最大值。 通过这样做，你将再次允许轴自动计算出它的最大值。
            }
        }
        //自定义x轴显示内容
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                String tradeDate = xData.get((int) value % xData.size());
                return tradeDate;
            }
        });
        //自定义y轴显示内容
//        YAxis leftYAxis = lineChart.getAxisLeft();
//        leftYAxis.setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
//                return value + "";
//            }
//        });
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        //LINEAR 折线图  CUBIC_BEZIER 圆滑曲线
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        //线条自定义内容 放在这里
        lineDataSet.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
                return value + "";
            }
        });
        LineData lineData = new LineData(lineDataSet);
        //设置是否显示节点值
        lineData.setDrawValues(false);
        lineChart.setData(lineData);

        //设置节点点击悬浮窗
        final IMarket iMarket = new IMarket();
        lineChart.setMarker(iMarket);
        lineChart.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                iMarket.refreshContent(e, h);
            }

            @Override
            public void onNothingSelected() {}
        });

        lineChart.notifyDataSetChanged();
        lineChart.invalidate();
    }

    private int getmColor(int colorId){
        return getResources().getColor(colorId);
    }

}
